package pub.tbc.api.helper;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import pub.tbc.toolkit.Objs;

import static io.netty.handler.codec.http.HttpHeaderNames.*;
import static io.netty.handler.codec.http.HttpResponseStatus.*;
import static io.netty.handler.codec.http.HttpResponseStatus.SERVICE_UNAVAILABLE;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * http异常响应辅助类
 *
 * @author tbc on 2017/3/18.
 */
@Slf4j
public class HttpResponseHelper {

    public static ChannelFuture generalResponse(ChannelHandlerContext ctx, HttpResponseStatus status, String msg) {
        if (Objs.isEmpty(msg)) msg = "Failure: " + status.toString() + "\r\n";
        ByteBuf body = Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
        FullHttpResponse response = new DefaultFullHttpResponse(
                HTTP_1_1,
                status,
                body
        );
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        response.headers().set(CONTENT_LENGTH, body.readableBytes());
        return ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    public static ChannelFuture badRequest(ChannelHandlerContext ctx, String msg) {
        return generalResponse(ctx, BAD_REQUEST, msg);
    }

    public static ChannelFuture unauthorized(ChannelHandlerContext ctx, String msg) {
        return generalResponse(ctx, UNAUTHORIZED, msg);
    }

    public static ChannelFuture notFound(ChannelHandlerContext ctx, String msg) {
        return generalResponse(ctx, NOT_FOUND, msg);
    }

    public static ChannelFuture methodNotAllowed(ChannelHandlerContext ctx, String msg) {
        return generalResponse(ctx, METHOD_NOT_ALLOWED, msg);
    }

    public static ChannelFuture unsupportedMediaType(ChannelHandlerContext ctx, String msg) {
        return generalResponse(ctx, UNSUPPORTED_MEDIA_TYPE, msg);
    }

    public static ChannelFuture internalServerError(ChannelHandlerContext ctx, String msg) {
        return generalResponse(ctx, INTERNAL_SERVER_ERROR, msg);
    }

    public static ChannelFuture badGateway(ChannelHandlerContext ctx, String msg) {
        return generalResponse(ctx, BAD_GATEWAY, msg);
    }

    public static ChannelFuture serviceUnavailable(ChannelHandlerContext ctx, String msg) {
        return generalResponse(ctx, SERVICE_UNAVAILABLE, msg);
    }


}
